import router from './router'
import { progressStart, progressDone } from "@/utils/nprogress"
import { isPathMatch, isHttp } from '@/utils/validate'
import { getToken } from '@/utils/auth'
import usePermissionStore from '@/store/modules/permission'

const whiteList = ['/login']

const isWhiteList = (path) => {
  return whiteList.some(pattern => isPathMatch(pattern, path))
}

router.beforeEach((to, from, next) => {
  progressStart()
  if (getToken()) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else if (isWhiteList(to.path)) {
      next()
    } else {
      if (usePermissionStore().sidebarRouters.length == 0) {
        usePermissionStore().generateRoutes().then(accessRoutes => {
          // 根据roles权限生成可访问的路由表
          accessRoutes.forEach(route => {
            if (!isHttp(route.path)) {
              router.addRoute(route) // 动态添加可访问路由表
            }
          })
          next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
        })
      } else {
        next()
      }
    }
  } else {
    if (isWhiteList(to.path)) {
      next()
    } else {
      next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
      progressDone()
    }
  }
})

router.afterEach(() => {
  progressDone()
})